package com.aitao.util.cmd;

import com.aitao.util.Validator;

import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 命令行默认实现
 *
 * @Company QAX
 * @Author : ai.tao
 * @Create : 2022/2/25 17:06
 */
public class DefaultCmdRunner implements CmdRunner {
    private ProcessBuilder pb;

    @Override
    public Cmd run(Path workDir, CharSequence... command) throws IOException {
        pb = new ProcessBuilder(formatCmd(Stream.of(command).collect(Collectors.toList())));
        return getCmd(workDir);
    }

    @Override
    public Cmd run(Path workDir, List<CharSequence> command) throws IOException {
        pb = new ProcessBuilder(formatCmd(command));
        return getCmd(workDir);
    }

    @Override
    public Cmd run(CharSequence command) throws IOException {
        return run(null, command);
    }

    @Override
    public Cmd run(List<CharSequence> command) throws IOException {
        return run(null, command);
    }

    private Cmd getCmd(Path workDir) throws IOException {
        if (Validator.isNotEmpty(workDir)) {
            pb.directory(workDir.toFile());
        }
        return new Cmd(pb.start());
    }

    private List<String> formatCmd(List<CharSequence> command) {
        List<String> cmdList = new ArrayList<>();
        for (CharSequence cmd : command) {
            StringTokenizer tokenizer = new StringTokenizer(cmd.toString());
            while (tokenizer.hasMoreTokens()) {
                cmdList.add(tokenizer.nextToken());
            }
        }
        return cmdList;
    }
}
